package es

import (
	"context"
	"encoding/json"
	"io"
	"k8s-events-collector/config"
	"log"
	"strings"

	"github.com/elastic/go-elasticsearch/v7"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"go.uber.org/zap"
)

type Events struct {
	Cluster   string `json:"cluster"`
	Time      string `json:"time"`
	Namespace string `json:"namespace"`
	Kind      string `json:"kind"`
	Name      string `json:"name"`
	Type      string `json:"type"`
	Reason    string `json:"reason"`
	Message   string `json:"message"`
}

func GetEsClient() (*elasticsearch.Client, error) {
	cfg := elasticsearch.Config{
		Addresses: []string{
			config.C.Es.GetEsDsn(),
		},
		Username: config.C.Es.Username,
		Password: config.C.Es.Password,
	}
	es, err := elasticsearch.NewClient(cfg)
	log.Println(elasticsearch.Version)
	log.Println(es.Info())
	if err != nil {
		zap.L().Sugar().Fatalf("GetEsClient.NewClient", err.Error())
		return nil, err
	}
	return es, nil
}

func (e *Events) Req(es *elasticsearch.Client) {
	data, err := json.Marshal(e)
	if err != nil {
		zap.L().Sugar().Fatal(err)
	}
	zap.L().Sugar().Info(string(data))
	req := esapi.IndexRequest{
		Index: config.C.Es.Index,
		Body:  strings.NewReader(string(data)),
	}

	res, err := req.Do(context.Background(), es)
	if err != nil {
		zap.L().Sugar().Fatal(err)
	}
	defer res.Body.Close()

	if res.IsError() {
		body, _ := io.ReadAll(res.Body)
		zap.L().Sugar().Fatal(string(body), res.Status())
	}
}
